package com.laikan.reader.bookreader.activity;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.*;
import android.widget.*;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.AndroidUtils;
import com.laikan.library.utils.SPUtil;
import com.laikan.library.viewop.ViewOperation;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookreader.engines.PageFactory;
import com.laikan.reader.bookreader.engines.PageStyleSet;
import com.laikan.reader.bookreader.engines.ScanView;
import com.laikan.reader.bookreader.engines.ScanViewAdapter;
import com.laikan.reader.bookreader.util.ChapterUtil;
import com.laikan.reader.bookreader.util.ReaderDetailUtil;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.*;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.laikan.reader.database.DBHistory;
import com.laikan.reader.database.History;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阅读详情页
 */
public class ReaderDetailActivity extends BasicActivity implements OnClickListener {

    public Drawable drawable_xiao, drawable_zhong, drawable_da;
    public Drawable drawable_xiao_r, drawable_zhong_r, drawable_da_r;
    public Drawable drawable_border, drawable_border_r;
    public ScanView document;
    public LinearLayout lin_bottom, lin_setting, shoucang_layout;
    public RelativeLayout lin_top, rel_plan, linear_top;
    public boolean xs_flag;
    public TextView shoucang_text, cancel_text;
    public ImageView back_tv;
    public TextView image_pinglun;
    public TextView image_dashan, lin_buy_bg;
    public RelativeLayout jianju_xiao, jianju_zhong, jianju_da;
    public RelativeLayout rela_back;
    public ImageView jianju_xiao_image, jianju_zhong_image, jianju_da_image;
    public ImageView iv_mulu; // 底部菜单:目录
    public ImageView iv_font; // 底部菜单:字体
    public ImageView iv_reader_mode; // 底部菜单:日间/夜间模式
    public Bitmap read_xiao, read_zhong, read_da, read_border;
    private ImageView iv_btn01, iv_btn02, iv_btn03, iv_btn07, iv_btn08;
    public SeekBar seekBar1, seekBar2;
    public TextView plan_text, plan_s_img, plan_x_img;
    public LinearLayout model, ziti_jia, ziti_jian, setting, catalog, new_bottom_menu;
    public ImageView image_more;
    public RelativeLayout rl_more;
    public TextView tv_bookdes;
    public TextView cb_zdbuy;
    public RelativeLayout rl_plan; // 上一章下一章整体控件
    public TextView setting_more, fontSizeShow;
    public BitmapDrawable draw_mulu;
    public BitmapDrawable draw_font;
    public BitmapDrawable draw_mode_r;
    public BitmapDrawable draw_mode_n;
    public Bitmap read_mulu;
    public Bitmap read_font;
    public Bitmap read_mode_r;
    public Bitmap read_mode_n;
    public Bitmap zitijiaBitmap, zitijianBitmap;
    public Drawable czitijia, czitijian;
    public ImageView image_jian, image_jia;
    public Bitmap buy_b, huiying_b, dashang_b, more_b;
    public Drawable back_d, buy_d, huiying_d, dashang_d, more_d;
    public Bitmap back_b;
    public RelativeLayout lk_reader_bg_img;
    public TextView chapter_name;
    public ProgressBar progress;
    public LinearLayout botton_space;
    private Animation animation, animation1;
    private PageStyleSet pss;
    private PageFactory pageFactory;
    private ScanViewAdapter adapter;
    private AlertDialog log;
    private List<ChapterBean> upchapter = new ArrayList<>();
    private TextView zhangjie_name;
    private String bookid, bookname, writername, bookicon;
    private ArrayList<ChapterBean> chaterData = new ArrayList<>();
    private CheckBox checkBox1;
    private View zzc_view;
    private boolean isFullPresent = false;  //是否为出版物
    private Book bookDes;
    private RelativeLayout seekbar_rela;
    private PopupWindow window;
    private Drawable img_on, img_off;
    private Resources res;
    private boolean isSetting = false;
    private boolean isShow = false;
    private View contentView;
    /*** 屏幕宽度*/
    private int screenW;
    /*** 屏幕高度*/
    private int screenH;
    private BaseDataBean<BaseListDataBean<ChapterBean>> chapter_data = null;
    private List<ChapterBean> chapterWithoutVolume = null; //章节目录过滤卷
    private String groupId;
    private boolean IsMoreShow = false;
    public TextView reader_tx_allday, reader_tx_setting, reader_tx_mulu;
    private ReaderViewLoadingDialog mReaderViewLoadingDialog;
    private RelativeLayout all_add_bookshelf;
    public boolean isRefreshBookChapter = false;
    Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 3:
                    isUpdateBookDirectory(bookid, bookDes.getUpdateTime());
                    break;
                case 7:
                    showPickDialog();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void onPause() {
        super.onPause();
        if (adapter != null) {
            SPUtil.putInt(bookid + "chaptep_rec", adapter.getChapterIdIndex());
            SPUtil.putInt(bookid + "recCurPage", adapter.getIndex());
            SPUtil.putInt(bookid + "shelf_index", adapter.getChapterIdIndex());
            SPUtil.putString(bookid + "shelf_chaptername", adapter.chapData.get(adapter.getChapterIdIndex()).getName());
            if (DBBook.getInstance().queryBookById(bookDes.getId()) != null){
                bookDes.setIsUpdated(false);
                DBBook.getInstance().insertBook(bookDes);
            }
            History h = bookDes.convertHistory();
            h.setLastReadChapter(adapter.chapData.get(adapter.getChapterIdIndex()).getName());
            h.setLastReadTime(System.currentTimeMillis());
            LaiKanEvent event = LaiKanEvent.getInstance();
            event.setEventID(LaiKanEvent.EVENT_ID_ADD_READ_HISTORY);
            event.setElves(h);
            postEvent(event);
        }
        MobclickAgent.onPause(this);
        if (Build.VERSION.SDK_INT >= 14) {
            ReaderDetailUtil.cancelFullScreen(mContext);
        }
    }

    @Override
    protected void assignViews() {
        openEventBus();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.lk_reader_detail);
        ReaderDetailUtil.setFullScreen(mContext);
        all_add_bookshelf = (RelativeLayout)findViewById(R.id.all_add_bookshelf);
        botton_space = (LinearLayout)findViewById(R.id.botton_space);
        mReaderViewLoadingDialog = new ReaderViewLoadingDialog(this);
        rela_back = (RelativeLayout)findViewById(R.id.rela_back);
        chapter_name = (TextView)findViewById(R.id.chapter_name);
        progress = (ProgressBar)findViewById(R.id.progress);
        lk_reader_bg_img = (RelativeLayout)findViewById(R.id.lk_reader_bg_img);
        zhangjie_name = (TextView)findViewById(R.id.zhangjie_name);
        seekbar_rela = (RelativeLayout)findViewById(R.id.seekbar_rela);
        rl_plan = (RelativeLayout)findViewById(R.id.rl_plan);
        jianju_xiao = (RelativeLayout)findViewById(R.id.jianju_xiao);
        jianju_zhong = (RelativeLayout)findViewById(R.id.jianju_zhong);
        jianju_da = (RelativeLayout)findViewById(R.id.jianju_da);
        jianju_xiao_image = (ImageView)findViewById(R.id.jianju_xiao_image);
        jianju_zhong_image = (ImageView)findViewById(R.id.jianju_zhong_image);
        jianju_da_image = (ImageView)findViewById(R.id.jianju_da_image);
        shoucang_text = (TextView)findViewById(R.id.shoucang_text);
        cancel_text = (TextView)findViewById(R.id.cancel_text);
        shoucang_layout = (LinearLayout)findViewById(R.id.shoucang_layout);
        zzc_view = findViewById(R.id.zzc_view);
        checkBox1 = (CheckBox)findViewById(R.id.checkBox1);
        seekBar2 = (SeekBar)findViewById(R.id.seekBar2);
        plan_s_img = (TextView)findViewById(R.id.plan_s_img);
        plan_x_img = (TextView)findViewById(R.id.plan_x_img);
        plan_text = (TextView)findViewById(R.id.plan_text);
        rel_plan = (RelativeLayout)findViewById(R.id.rel_plan);
        seekBar1 = (SeekBar)findViewById(R.id.seekBar1);
        ziti_jian = (LinearLayout)findViewById(R.id.ziti_jian);
        ziti_jia = (LinearLayout)findViewById(R.id.ziti_jia);
        image_jian = (ImageView)findViewById(R.id.image_jian);
        image_jia = (ImageView)findViewById(R.id.image_jia);
        lin_bottom = (LinearLayout)findViewById(R.id.lin_bottom);
        lin_top = (RelativeLayout)findViewById(R.id.lin_top);
        linear_top = (RelativeLayout)findViewById(R.id.linear_top);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        model = (LinearLayout)findViewById(R.id.model);
        setting = (LinearLayout)findViewById(R.id.setting);
        catalog = (LinearLayout)findViewById(R.id.catalog);
        image_dashan = (TextView)findViewById(R.id.image_dashan);
        lin_buy_bg = (TextView)findViewById(R.id.lin_buy_bg);
        image_pinglun = (TextView)findViewById(R.id.image_pinglun);
        lin_setting = (LinearLayout)findViewById(R.id.lin_settings);
        image_more = (ImageView)findViewById(R.id.image_more);
        iv_mulu = (ImageView)findViewById(R.id.iv_mulu);
        iv_font = (ImageView)findViewById(R.id.iv_font);
        iv_reader_mode = (ImageView)findViewById(R.id.iv_reader_mode);
        iv_btn01 = (ImageView)findViewById(R.id.iv_btn01);
        iv_btn02 = (ImageView)findViewById(R.id.iv_btn02);
        iv_btn03 = (ImageView)findViewById(R.id.iv_btn03);
        iv_btn07 = (ImageView)findViewById(R.id.iv_btn07);
        iv_btn08 = (ImageView)findViewById(R.id.iv_btn08);
        // 初始化自动订阅的选中和未选中的背景图片
        res = getResources();
        img_off = res.getDrawable(R.drawable.ic_choice_norma);
        img_on = res.getDrawable(R.drawable.ic_choice_selected);
        img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
        img_on.setBounds(0, 0, img_on.getMinimumWidth(), img_on.getMinimumHeight());
        new_bottom_menu = (LinearLayout)findViewById(R.id.new_bottom_menu);
        setting_more = (TextView)findViewById(R.id.setting_more);
        fontSizeShow = (TextView)findViewById(R.id.fontSize);
        fontSizeShow.setText(SPUtil.getInt("fontSize", 18) + "");

        contentView = View.inflate(this, R.layout.popupwindow_checkbox, null);
        rl_more = (RelativeLayout)contentView.findViewById(R.id.rl_more);
        tv_bookdes = (TextView)contentView.findViewById(R.id.tv_bookdes); // 书籍详情
        cb_zdbuy = (TextView)contentView.findViewById(R.id.cb_zdbuy); // 自动购买
        reader_tx_allday = (TextView)findViewById(R.id.reader_tx_allday);
        reader_tx_setting = (TextView)findViewById(R.id.reader_tx_setting);
        reader_tx_mulu = (TextView)findViewById(R.id.reader_tx_mulu);

    }

    @Override
    protected void initData() {
        ReaderDetailUtil.setbg(SPUtil.getInt("bg_model", 0), this);
        SPUtil.putBoolean("DoubleVis", false);
        openEventBus();
        chapterWithoutVolume = new ArrayList<>();
        // 获取屏幕宽高
        screenW = this.getWindowManager().getDefaultDisplay().getWidth();
        screenH = this.getWindowManager().getDefaultDisplay().getHeight();
        seekBar1.setProgress((int)(getScreenBrightness() / 2.55));
        Intent intent = getIntent();
        bookDes = (Book)getIntent().getSerializableExtra("bookDes");
        bookid = bookDes.getId();
        bookname = bookDes.getName();
        writername = bookDes.getAuthorName();
        bookicon = bookDes.getIcon();
        groupId = intent.getStringExtra("groupId");
        if ("3".equals(groupId)) {
            isFullPresent = true;
        }

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, MathUtil.dip2px(this, 48));
        lp.setMargins(0, AndroidUtils.getTitleBarHeight(mContext), 0, 0);
        lin_top.setLayoutParams(lp);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int actionbar = AndroidUtils.getVirtualKeyHeight(this);
            ViewOperation.setRelaViewHeight(botton_space, actionbar);
            ViewOperation.setRelaViewMarginDistance(lin_bottom, 0, 0, 0, actionbar);
            ViewOperation.setRelaViewMarginDistance(lin_setting, 0, 0, 0, actionbar);
            ViewOperation.setRelaViewMarginDistance(shoucang_layout, 0, 0, 0, actionbar);
        }
        // 获取书籍详情
        getChapterData();

        // 下载章节目录
        animation = AnimationUtils.loadAnimation(this, R.anim.bottom_to_top);
        animation1 = AnimationUtils.loadAnimation(this, R.anim.top_to_bottom);
        // 初始化显示调用系统自动调节屏幕亮度设置
        if (SPUtil.getBoolean("isAutoBrightness", false)) {
            setScreenBrightness(getScreenBrightness());
            checkBox1.setChecked(true);
        }else {
            checkBox1.setChecked(false);
        }
        ReaderDetailUtil.initBmp(this);
        ReaderDetailUtil.setIntervalBtn(this, SPUtil.getInt("content_interval", 2));
        setBackground();

    }

    /**
     * onActivityResult 返回数据处理
     */
    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // 从目录返回，带有参数
        if (arg0 == 1) {
            adapter.setFontType();
        }
//        if (1234 == arg0 && null != arg2) {
//            boolean b = arg2.getBooleanExtra("isResOpenDoc", false);
//
//        }
        super.onActivityResult(arg0, arg1, arg2);
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        super.parseEvent(event);
        switch (event.getEventID()){
            case LaiKanEvent.EVENT_ID_READERDETAIL_CHAPTER_REFRESH:
                HashMap<String, Object> map = (HashMap<String, Object>)event.getEventMap();
                boolean isResOpenDoc = (boolean)map.get("isResOpenDoc");
                if (isResOpenDoc) {
                    ArrayList<ChapterBean> aa = (ArrayList<ChapterBean>)map.get("chapterData");
                    if (chaterData.size() != aa.size()) {
                        adapter.chapData.clear();
                        adapter.chapData = aa;
                    }
                    adapter.getRecContent(true);
                }
                break;
            case LaiKanEvent.EVENT_ID_ADD_READ_HISTORY:
                History h = (History)event.getElves();
                DBHistory.getInstance().insertHistory(h);
//
                break;
            default:
                break;
        }
    }

    @Override
    protected void setListener() {
        all_add_bookshelf.setOnClickListener(this);
        jianju_da.setOnClickListener(this);
        jianju_xiao.setOnClickListener(this);
        jianju_zhong.setOnClickListener(this);
        cancel_text.setOnClickListener(this);
        shoucang_text.setOnClickListener(this);
        zzc_view.setOnClickListener(this);
        plan_s_img.setOnClickListener(this);
        plan_x_img.setOnClickListener(this);
        ziti_jia.setOnClickListener(this);
        ziti_jian.setOnClickListener(this);
        rela_back.setOnClickListener(this);
        model.setOnClickListener(this);
        setting.setOnClickListener(this);
        catalog.setOnClickListener(this);
        image_dashan.setOnClickListener(this);
        image_pinglun.setOnClickListener(this);
        image_more.setOnClickListener(this); // 菜单右上角的更多
        lin_setting.setOnClickListener(this);
        lin_top.setOnClickListener(this);
        rl_plan.setOnClickListener(this);

        iv_btn01.setOnClickListener(this);
        iv_btn02.setOnClickListener(this);
        iv_btn03.setOnClickListener(this);
        iv_btn07.setOnClickListener(this);
        iv_btn08.setOnClickListener(this);
        setting_more.setOnClickListener(this);
        // 自动亮度
        checkBox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    seekBar1.setProgress((int)(getScreenBrightness() / 2.55));
                    setScreenBrightness(getScreenBrightness());
                    checkBox1.setChecked(true);
                    SPUtil.putBoolean("isAutoBrightness", true);
                }else {
                    SPUtil.putBoolean("isAutoBrightness", false);
                }
            }
        });
        // 阅读进度条
        seekBar2.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int progressIn;

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO 进度条 定位
                seekbar_rela.setVisibility(View.INVISIBLE);
                adapter.referPage(progressIn);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    progressIn = progress;
                    zhangjie_name.setText(adapter.getChapterName());
                    seekbar_rela.setVisibility(View.VISIBLE);
                    plan_text.setText(progress + 1 + "/" + adapter.getChapterPageSize());
                }

            }
        });

        // 亮度进度条
        seekBar1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                checkBox1.setChecked(false);
                SPUtil.putBoolean("isAutoBrightness", false);
                if (progress > 10) {
                    setScreenBrightness((int)(progress * 2.55));

                }

            }
        });

        // 顶部菜单购买
        lin_buy_bg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ReaderDetailActivity.this, "lk_buy_more");

                if (BookFileUtils.isNoLogin()) {
                    // 未登录
                    Intent intent = new Intent(ReaderDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                }else {
                    // 登录
                    bulkPurchase(true, 2, false);
                }
            }

        });
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     */
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 批量购买
     * boo 通知是否刷新页面
     *
     * @date 2015-11-20 下午2:33:53
     */
    public synchronized void bulkPurchase(boolean boo, int type, boolean isVis) {

        if (SPUtil.getBoolean("DoubleVis", false)) {
            return;
        }
        SPUtil.putBoolean("DoubleVis", true);
        if (isFullPresent) {
            if (isForeground(this, "DesBookBuy")) {
                return;
            }
            String startId;
            if (type == 1) {
                startId = adapter.getChargeCurrChapterId();
            }else if (type == 2) {
                startId = adapter.getChargeNextChapterId();
            }else if (type == 0) {
                startId = adapter.getChargePreChapterId();
            }else {
                startId = adapter.getChargeNextChapterId();
            }

            Intent intent = new Intent();
            intent.setClass(ReaderDetailActivity.this, DesBookBuy.class);
            intent.putExtra("bookName", bookname);
            intent.putExtra("bookId", bookid);
            intent.putExtra("chid", startId);
            intent.putExtra("typeRef", type);
            intent.putExtra("type", type);
            intent.putExtra("writername", writername);
            intent.putExtra("isFollow", DBBook.getInstance().queryBookById(bookid));
            Bundle bundle = new Bundle();
            bundle.putSerializable("bookDes", bookDes);
            intent.putExtras(bundle);
            startActivity(intent);

            // 出版物
        }else {

            // 非出版物
            if (isForeground(this, "DesChapterBuy")) {
                return;
            }
            Intent intent = new Intent();
            // 批量购买修改
            intent.setClass(ReaderDetailActivity.this, DesChapterBuy.class);
            intent.putExtra("book_id", bookid);
            intent.putExtra("bookName", bookname);
            intent.putExtra("notiPage", boo);
            intent.putExtra("isVis", isVis);
            intent.putExtra("state", "1");
            intent.putExtra("typeRef", type);
            intent.putExtra("writername", writername);
            if (type == 1) {
                intent.putExtra("startChapeterID", adapter.getChargeCurrChapterId());
            }else if (type == 2) {
                intent.putExtra("startChapeterID", adapter.getChargeNextChapterId());
            }else if (type == 0) {
                intent.putExtra("startChapeterID", adapter.getChargePreChapterId());
                if (adapter.getChargePreChapterId().equals("")) {
                    ToastMgr.showShortToast(R.string.bookreader_not_forward_flip);
                    return;
                }
            }else {
                intent.putExtra("startChapeterID", adapter.getChargeNextChapterId());
            }
            intent.putExtra("isReOpenBook", true);      // 购买后刷新阅读页
            // 传递书籍详情信息
            Bundle bundle = new Bundle();
            bundle.putSerializable("bookDes", bookDes);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        if (SPUtil.getBoolean("isChapterRefer", false)) {
            SPUtil.putBoolean("isChapterRefer", false);
            adapter.getRecContent(true);
        }
        if(isRefreshBookChapter){
            isRefreshBookChapter = false;
            handler.sendEmptyMessage(8);
            gotoBookChapter();
        }
        if (SPUtil.getBoolean("IsRefer", false)) {
            SPUtil.putBoolean("IsRefer", false);
            int aa = SPUtil.getInt("typeRef", -1);
            if (adapter != null) {
                SPUtil.putInt("typeRef", -1);
                if (aa == 1) {
                    adapter.setCurrReloadNotFree();
                }else if (aa == 2) {
                    SPUtil.putInt(bookid + "chaptep_rec", SPUtil.getInt(bookid + "chaptep_rec", 0) + 1);
                    SPUtil.putInt(bookid + "recCurPage", 0);
                    adapter.getRecContent(true);
                }else if (aa == 0) {
                    SPUtil.putInt(bookid + "chaptep_rec", SPUtil.getInt(bookid + "chaptep_rec", 0) - 1);
                    SPUtil.putInt(bookid + "recCurPage", 0);
                    adapter.getRecContent(true);
                }

            }

        }
        super.onResume();
        MobclickAgent.onResume(this);
        xiaoshi();
        ReaderDetailUtil.setFullScreen(mContext);
    }

    public void gotoBookChapter() {
        Intent intent1 = new Intent();
        intent1.setClass(this, BookChapter.class);
        intent1.putExtra("book_id", bookid);
        intent1.putExtra("bookName", bookname);
        intent1.putExtra("groupId", groupId);
        intent1.putExtra("writername", writername);
        intent1.putExtra("rEyeshield", true);
        intent1.putExtra("bookDes", bookDes);
        startActivityForResult(intent1, 1234);
        // xiaoshi(false);
        isSetting = false;
        IsMoreShow = true;
    }

    /**
     * 隐藏功能性菜单栏
     */
    public void xiaoshi() {
        ReaderDetailUtil.setFullScreen(mContext);
        xs_flag = false;
        seekbar_rela.setVisibility(View.GONE);
        lin_bottom.setVisibility(View.GONE);
        if (!IsMoreShow) {
            lin_bottom.startAnimation(animation1);
            IsMoreShow = true;
        }
        lin_top.setVisibility(View.GONE);
        linear_top.setVisibility(View.GONE);
        lin_setting.setVisibility(View.GONE);
        if (isSetting) {
            isSetting = false;
            lin_setting.startAnimation(animation1);
        }
        rel_plan.setVisibility(View.GONE);
        zzc_view.setVisibility(View.GONE);
        dismiss();
    }

    /**
     * 是否收藏
     */
    private void check_stow() {
        if (!shoucang_layout.isShown() && DBBook.getInstance().queryBookById(bookid) == null) {
            all_add_bookshelf.setVisibility(View.VISIBLE);
            shoucang_layout.setVisibility(View.VISIBLE);
            shoucang_layout.startAnimation(animation);
        }else {
            shoucang_layout.setVisibility(View.GONE);
            shoucang_layout.startAnimation(animation1);
        }
    }

    /**
     * 隐藏点击更多:显示的自动订阅
     */
    public void dismiss() {
        isShow = false;
        if (window != null && window.isShowing()) {
            window.dismiss();
        }
    }

    /**
     * 设置当前屏幕亮度值 0--255
     */
    @SuppressWarnings ("unused")
    private void saveScreenBrightness(int paramInt) {
        try {
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, paramInt);
        }catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    /**
     * 获得当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    @SuppressWarnings ("unused")
    private int getScreenMode() {
        int screenMode = 0;
        try {
            screenMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        }catch (Exception localException) {

        }
        return screenMode;
    }

    /**
     * 获得当前屏幕亮度值 0--255
     */
    private int getScreenBrightness() {
        int screenBrightness = 255;
        try {
            screenBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        }catch (Exception localException) {

        }
        return screenBrightness;
    }

    /**
     * 保存当前的屏幕亮度值，并使之生效
     */
    private void setScreenBrightness(int paramInt) {
        Window localWindow = getWindow();
        WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
        float f = paramInt / 255.0F;
        localLayoutParams.screenBrightness = f;
        localWindow.setAttributes(localLayoutParams);
    }

    /**
     * 获取章节数据
     */
    private void getChapterData() {
        try {
            BaseDataBean<BaseListDataBean<ChapterBean>> localChapterData;
            localChapterData = ChapterUtil.getChapterDataFromLocal(bookid);
            // 判断目录文件是否存在
            if (localChapterData != null) {
                KLog.i(bookname + "目录文件存在");
                setBookDirectory(localChapterData);
                new Thread() {
                    @Override
                    public void run() {
                        SPUtil.putString(bookid + "_lastChapterId", chaterData.get(chaterData.size() - 1).getId());
                        BookFileUtils.totalChapter(bookid, chaterData);
                        handler.sendEmptyMessage(3);
                        super.run();
                    }
                }.start();
                // 2.记录最后章节id

            }else {
                // 文件不存在,下载目录
                if (ActivityUitl.isNetworkAvailable(mContext)) {
                    getChapterDataFromServer(bookid, false);
                }else {
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1500);

                }

                KLog.i(bookname + "目录文件不存在,下载目录文件");
            }
        }catch (Exception e) {
            KLog.e("getChapterData() " + e.getMessage());
            ToastMgr.showShortToast(R.string.bookreader_books_open_failed);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 1500);
        }
    }

    /**
     * 根据本地最后章节id和网络端最后章节id对比, 如果不一致则更新该书籍目录
     *
     * @param lastUpdataTime 本地端最后章节id
     */
    private void isUpdateBookDirectory(final String bookId, final String lastUpdataTime) {
        boolean isNet = PublicUtil.isNetworkAvailable(this);
        if (isNet) {
            getChapterDataFromServer(bookId, true);
            // KLog.e("949  重新获取" + bookId + "目录" + "当前UpdataTime = " + lastUpdataTime + ";网络最新UpdataTime = " + b.getUpdateTime());
        }
    }
    /**
     * 显示设置头像的对话框
     */
    private void showPickDialog() {

        if (log == null) {
            log = new AlertDialog.Builder(mContext).setView(View.inflate(mContext, R.layout.alterdialog, null)).setNegativeButton("登录", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("isChapterRefer", true);
                    startActivityForResult(intent, 2);
                }
            }).setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }else {
            log.show();
        }

    }

    /**
     * 设置目录数据
     *
     * @param data 解析json文件后的对象
     */
    private void setBookDirectory(BaseDataBean<BaseListDataBean<ChapterBean>> data) {

        if (data != null) {
            // 1.获取章节目录
            chaterData = data.getData().getData();
            writername = data.getData().getAuthorName();
            for (int i = 0; i < chaterData.size(); i++) {
                if (!chaterData.get(i).isVolume()) {
                    chapterWithoutVolume.add(chaterData.get(i));
                }
            }
            if (SPUtil.getInt(bookid + "chaptep_rec", 0) == -1) {
                SPUtil.putInt(bookid + "chaptep_rec", 0);
            }
            chapter_name.setText(chapterWithoutVolume.get(SPUtil.getInt(bookid + "chaptep_rec", 0)).getName());
            document = (ScanView)findViewById(R.id.document);
            PageStyleSet.screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
            PageStyleSet.screenHeight = getWindowManager().getDefaultDisplay().getHeight(); // 屏幕高（像素，如：800p）
            PageStyleSet.density = getResources().getDisplayMetrics().density;
            PageStyleSet.scaledDensity = getResources().getDisplayMetrics().scaledDensity;
            pss = PageStyleSet.Instance();
            pss.Init(mContext);
            pageFactory = new PageFactory(pss, mContext, bookname);
            adapter = new ScanViewAdapter(this, pageFactory, pss, document, chapterWithoutVolume, bookid,bookname, groupId);
            adapter.setOnBuyListener(new ScanViewAdapter.OnBuyListener() {
                @Override
                public void setBuy(int type) {
                    if (SystemUtil.isLogin()) {
                        bulkPurchase(true, type, true);
                    }else {
                        handler.sendEmptyMessage(7);
                    }
                }
            });
            document.setOnMenuListener(new ScanView.OnMenuListener() {
                @Override
                public void setShowMenuListener() {
                    seekBar2.setMax(adapter.getChapterPageSize() - 1);
                    if (!shoucang_layout.isShown()) {

                        if (!xs_flag) {
                            xs_flag = !xs_flag;
                            // TODO 退出全屏

                            lin_bottom.setVisibility(View.VISIBLE);
                            lin_bottom.startAnimation(animation);
                            lin_top.setVisibility(View.VISIBLE);
                            linear_top.setVisibility(View.VISIBLE);
                            zzc_view.setVisibility(View.VISIBLE);
                            rel_plan.setVisibility(View.VISIBLE);
                            seekBar2.setProgress(adapter.getIndex());
                            seekBar2.setMax(adapter.getChapterPageSize() - 1);
                            if (Build.VERSION.SDK_INT >= 14) {
                                ReaderDetailUtil.cancelFullScreen(mContext);
                                // getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                            }
                        }else {
                            // xiaoshi(true);
                        }
                    }else {
                        shoucang_layout.setVisibility(View.GONE);
                        shoucang_layout.startAnimation(animation1);
                    }

                }
            });


            // 3.判断是否是出版图书
            groupId = data.getData().getGroupId();
            if ("3".equals(groupId)) {
                isFullPresent = true;
            }

        }
    }

    private void getChapterDataFromServer(final String book_id2, final boolean isup) {

        Map<String, String> map = new HashMap<>();
        map.put("userId", SPUtil.getString("user_id", "0"));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {

                BaseDataBean<BaseListDataBean<ChapterBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ChapterBean>>>() {}.getType();
                result = gson.fromJson(httpResponse.responseContent, type);

                if (result != null) {
                    try {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            chaterData = result.getData().getData();
                            if (isup) {

                                for (int i = 0; i < chaterData.size(); i++) {
                                    if (!chaterData.get(i).isVolume()) {
                                        upchapter.add(chaterData.get(i));
                                    }
                                }
                                adapter.updataDirectory(upchapter);
                            }else {
                                setBookDirectory(result);
                            }
                            // 记录最后章节id
                            ArrayList<ChapterBean> data = result.getData().getData();
                            SPUtil.putString(book_id2 + "_lastChapterId", data.get(data.size() - 1).getId());
                            BookFileUtils.totalChapter(book_id2, data);
                            BookFileUtils.saveBookDirectory(httpResponse.responseContent, book_id2);
                        }
                    }catch (Exception e) {
                        // 数据解析失败
                        ToastMgr.showShortToast(R.string.laikan_data_load_exception);
                        e.printStackTrace();
                        return;
                    }

                }else {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    if(!isup){
                        finish();
                    }
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {

                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                if(!isup){
                    finish();
                }
                KLog.e("网络不给力，请重试。69");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "book/" + book_id2 + "/chapter?userId=" + SPUtil.getString("user_id", "0"));
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (window != null && window.isShowing()) {
            window.dismiss();
        }
    }

    /**
     * 购买页
     *
     * @param v
     */

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.all_add_bookshelf:
                shoucang_layout.setVisibility(View.GONE);
                shoucang_layout.startAnimation(animation1);
                all_add_bookshelf.setVisibility(View.GONE);
                break;
            case R.id.lin_settings:
            case R.id.lin_top:
            case R.id.rl_plan:
                // 无需做任何操作
                KLog.e("1274 无需做任何操作");
                break;
            case R.id.zzc_view:
                xiaoshi();
                break;
            case R.id.plan_s_img:// 上一章 按钮
                if (ReaderDetailUtil.preChapterButton()) {
                    adapter.preChapter();
                    seekBar2.setProgress(adapter.getIndex());
                    seekBar2.setMax(adapter.getChapterPageSize() - 1);
                }
                break;
            case R.id.plan_x_img:// 下一章 按钮
                if (ReaderDetailUtil.nexChapterButton()) {
                    adapter.nextChapter();
                    seekBar2.setProgress(adapter.getIndex());
                    seekBar2.setMax(adapter.getChapterPageSize() - 1);
                }
                break;
            case R.id.ziti_jia:// 字体加
                int fontSize = SPUtil.getInt("fontSize", 18);
                if (fontSize <= 30) {
                    fontSize += 2;
                    fontSizeShow.setText(fontSize + "");
                    SPUtil.putInt("fontSize", fontSize);
                    adapter.setFontSize(fontSize);
                }else {
                    ToastMgr.showShortToast(R.string.bookreader_font_has_maximum);
                }
                break;
            case R.id.ziti_jian: // 字体减
                int fontSize1 = SPUtil.getInt("fontSize", 18);
                if (fontSize1 >= 18) {
                    fontSize1 -= 2;
                    KLog.e("1170 fontSize = " + fontSize1);
                    fontSizeShow.setText(fontSize1 + "");
                    SPUtil.putInt("fontSize", fontSize1);
                    adapter.setFontSize(fontSize1);
                }else {
                    ToastMgr.showShortToast(R.string.bookreader_font_has_minimum);
                }
                break;
            case R.id.rela_back:// 返回按钮

                check_stow();
                if (DBBook.getInstance().queryBookById(bookid) == null) {
                    xiaoshi();
                }else {

                    finish();
                }
                break;

            case R.id.model:// 日间夜间切换
                boolean flag = SPUtil.getBoolean("model_flag", false);
                flag = !flag;
                isModel(flag);
                SPUtil.putBoolean("model_flag", flag);
                adapter.setNightModle(SPUtil.getInt("bg_model", 0));
                ReaderDetailUtil.changeColor(this);
                break;
            case R.id.setting:// 设置

                lin_bottom.setVisibility(View.GONE);
                // lin_bottom.startAnimation(animation1);
                lin_setting.setVisibility(View.VISIBLE);
                if (Build.VERSION.SDK_INT >= 14) {
                    ReaderDetailUtil.setFullScreen(mContext);
                }
                isSetting = true;
                linear_top.setVisibility(View.GONE);
                lin_setting.startAnimation(animation);
                rel_plan.setVisibility(View.GONE);

                dismiss();
                break;
            case R.id.catalog:// 跳转章节目录
               gotoBookChapter();
                break;
            case R.id.image_dashan:// 打赏
                MobclickAgent.onEvent(this, "readpage_boost");
                Intent intent2 = new Intent();
                intent2.setClass(this, RewardActivityNew.class);
                intent2.putExtra("bookId", bookid);
                intent2.putExtra("bookName", bookname);
                startActivity(intent2);
                isSetting = false;
                IsMoreShow = true;
                break;
            case R.id.image_pinglun:// 评论
                MobclickAgent.onEvent(this, "readpage_comment");
                startActivity(new Intent().setClass(getApplicationContext(), CommentActivity.class).putExtra("bookName", bookname).putExtra("bookId", bookid));
                isSetting = false;
                IsMoreShow = true;
                break;

            case R.id.cancel_text:
                setAnimToBottom();
                exit();
                break;
            case R.id.shoucang_text:// 收藏
                collect();
                break;
            case R.id.jianju_da:    // 设置间距大
                adapter.setLineSpace(0.75f);
                SPUtil.putInt("content_interval", 3);
                ReaderDetailUtil.setIntervalBtn(this, 3);
                MobclickAgent.onEvent(this, "lineSpacing_big");
                break;

            case R.id.jianju_zhong:    // 间距中
                adapter.setLineSpace(0.382f);
                SPUtil.putInt("content_interval", 2);
                ReaderDetailUtil.setIntervalBtn(this, 2);
                MobclickAgent.onEvent(this, "lineSpacing_middle");
                break;

            case R.id.jianju_xiao:    // 间距小
                adapter.setLineSpace(0.282f);
                SPUtil.putInt("content_interval", 1);
                ReaderDetailUtil.setIntervalBtn(this, 1);
                MobclickAgent.onEvent(this, "lineSpacing_small");
                break;

            case R.id.image_more:    // 菜单右上角更多

                morePopupWindow();
                break;
            case R.id.setting_more:    // 更多设置
                Intent intent = new Intent(ReaderDetailActivity.this, ReaderSettingMore.class);
                intent.putExtra("anim", SPUtil.getInt("PageFilp", 2));
                intent.putExtra("bookId", bookid);
                intent.putExtra("typeface_check_dex", SPUtil.getInt("typeface_check", 1));
                startActivityForResult(intent, 1);
                isSetting = false;
                IsMoreShow = true;
                break;
            default:
                break;
        }
        bgColorBtn(v);
    }

    /**
     * 切换背景颜色
     *
     * @param v 点中的view
     *
     * @date 2015-11-30 下午2:33:34
     */
    private void bgColorBtn(View v) {
        switch (v.getId()) {
            case R.id.iv_btn01:
                setBgBtnState(0, true);
                adapter.setBg(0);
                reader_tx_allday.setText(R.string.reader_detail_night);
                break;
            case R.id.iv_btn02:
                setBgBtnState(2, true);
                adapter.setBg(2);
                reader_tx_allday.setText(R.string.reader_detail_night);
                break;
            case R.id.iv_btn03:
                setBgBtnState(4, true);
                adapter.setBg(4);
                reader_tx_allday.setText(R.string.reader_detail_night);
                break;
            case R.id.iv_btn07:
                setBgBtnState(12, true);
                adapter.setBg(12);
                reader_tx_allday.setText(R.string.reader_detail_night);
                break;
            case R.id.iv_btn08:
                setBgBtnState(14, true);
                adapter.setBg(14);
                reader_tx_allday.setText(R.string.reader_detail_night);
                break;
            default:
                break;

        }
        ReaderDetailUtil.changeColor(this);
    }

    /**
     * 设置背景按钮的状态
     *
     * @param bg_model 使用的背景模式
     * @param flag true:设置背景颜色 false:不设置背景颜色
     *
     * @date 2015-11-30 下午4:41:47
     * @author yjh
     */
    private void setBgBtnState(int bg_model, boolean flag) {
        clearImgBtnSelected();
        switch (bg_model) {
            case 0:
                iv_btn01.setSelected(true);
                changeBgColor(iv_btn01, 0, R.drawable.lk_reader_bg1, flag);
                break;
            case 2:
                iv_btn02.setSelected(true);
                changeBgColor(iv_btn02, 2, R.color.C_CCEEDD, flag);
                break;
            case 4:
                iv_btn03.setSelected(true);
                changeBgColor(iv_btn03, 4, R.color.C_CCDDED, flag);
                break;

            case 12:
                iv_btn07.setSelected(true);
                changeBgColor(iv_btn07, 12, R.color.C_2A2A2A, flag);
                break;
            case 14:
                iv_btn08.setSelected(true);
                changeBgColor(iv_btn08, 14, R.color.C_17232F, flag);
                break;
        }
    }

    /**
     * 更改背景颜色
     *
     * @param v 选中的切换背景颜色的按钮
     * @param bg_model 使用的背景模式
     * @param resId 背景资源id
     * @param flag true:设置背景颜色 false:不设置背景颜色
     *
     * @date 2015-11-30 下午4:40:00
     */
    public void changeBgColor(ImageView v, int bg_model, int resId, boolean flag) {
        if (flag) {
            clearImgBtnSelected();
            v.setSelected(true);
            SPUtil.putBoolean("model_flag", false);
            SPUtil.putInt("bg_model", bg_model);

        }
    }

    /**
     * 清除所有背景按钮的选择状态
     *
     * @date 2015-11-30 下午3:24:03
     */
    private void clearImgBtnSelected() {
        iv_btn01.setSelected(false);
        iv_btn02.setSelected(false);
        iv_btn03.setSelected(false);
        iv_btn07.setSelected(false);
        iv_btn08.setSelected(false);
    }

    private void morePopupWindow() {
        if (isShow) { // 已显示状态
            dismiss();
            return;
        }
        if (!isShow) {    // 不显示状态
            isShow = true;
        }
        window = new PopupWindow(contentView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.getContentView().measure(0, 0);
        int windowW = window.getContentView().getMeasuredWidth() + MeasureUtil.px2dip(this, 10);
        window.showAsDropDown(lin_top, screenW - windowW, MeasureUtil.px2dip(this, 10));
        // 渐变动画
        AlphaAnimation aa = new AlphaAnimation(0.2f, 1.0f);
        aa.setDuration(200);
        // 缩放动画
        ScaleAnimation sa = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setDuration(200);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
        contentView.startAnimation(set);

        // 设置自动购买状态
        if (!SPUtil.getBoolean(bookid + "_zdbuy", false)) {
            cb_zdbuy.setCompoundDrawables(null, null, img_off, null); // 设置左图标
        }else {
            cb_zdbuy.setCompoundDrawables(null, null, img_on, null); // 设置左图标
        }
        // 自动购买
        cb_zdbuy.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (BookFileUtils.isNoLogin()) {
                    ToastMgr.showShortToast(R.string.personal_please_login);
                }else {

                    MobclickAgent.onEvent(ReaderDetailActivity.this, "lk_read_auto_buy");
                    if (!SPUtil.getBoolean(bookid + "_zdbuy", false)) {
                        // 设置左图标
                        cb_zdbuy.setCompoundDrawables(null, null, img_on, null);
                        SPUtil.putBoolean(bookid + "_zdbuy", true);
                    }else {
                        cb_zdbuy.setCompoundDrawables(null, null, img_off, null);
                        SPUtil.putBoolean(bookid + "_zdbuy", false);
                    }
                }
            }
        });

        // 查看详情
        tv_bookdes.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ReaderDetailActivity.this, "lk_read_des");
                Intent intent = new Intent();
                intent.setClass(ReaderDetailActivity.this, BookDesActivity.class);
                intent.putExtra("data", bookDes);
                startActivity(intent);
                isSetting = false;
                IsMoreShow = true;
            }
        });

    }

    /**
     * 收藏接口
     */
    private void collect() {
        showDialog();
        Map<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                dismissDialog();
                try {
                    DBBook.getInstance().insertBook(bookDes);
                    ToastMgr.showShortToast(R.string.bookshelf_book_added);
                    exit();
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。41");
                dismissDialog();
            }

            @Override
            public void onFinish() {
                dismissDialog();
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_follow + bookid + "/2/add");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_follow + bookid + "/2/add", map, null, null, requestListener);
    }

    // 取消显示
    private void setAnimToBottom() {
        shoucang_layout.setVisibility(View.GONE);
        shoucang_layout.startAnimation(animation1);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {

            case KeyEvent.KEYCODE_BACK:
                check_stow();

                if (DBBook.getInstance().queryBookById(bookid) == null) {
                    xiaoshi();
                }else {
                    finish();
                }
                return true;
            // 音量减小 往后翻页
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if(adapter.isNextPage(0)){
                    adapter.addIndex();
                    document.addNextPage();
                }
                return true;
            // 音量增大 往前翻页
            case KeyEvent.KEYCODE_VOLUME_UP:
                if(adapter.isPrePage()){
                    adapter.minusIndex();
                    document.addPrePage();
                }
                return true;

            case KeyEvent.KEYCODE_MENU:
                if (!xs_flag) {
                    xs_flag = !xs_flag;
                    if (Build.VERSION.SDK_INT >= 14) {
                        ReaderDetailUtil.cancelFullScreen(mContext);
                    }
                    lin_bottom.setVisibility(View.VISIBLE);
                    lin_bottom.startAnimation(animation);
                    lin_top.setVisibility(View.VISIBLE);
                    linear_top.setVisibility(View.VISIBLE);
                    zzc_view.setVisibility(View.VISIBLE);
                    rel_plan.setVisibility(View.VISIBLE);
                }else {
                    xiaoshi();
                }
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode==KeyEvent.KEYCODE_VOLUME_DOWN){

            return true;
        }
        else if(keyCode==KeyEvent.KEYCODE_VOLUME_UP)
        {

            return true;
        }
        else return super.onKeyUp(keyCode, event);
    }
    private void exit() {
        finish();
    }

    /**
     * 设置背景 备注: 初始化背景颜色在PageStyle类的init()方法中
     */
    private void setBackground() {
        boolean model_flag = SPUtil.getBoolean("model_flag", false);
        isModel(model_flag);

    }

    /**
     * 切换日夜间模式
     */
    private void isModel(boolean flag) {
        if (!flag) {
            reader_tx_allday.setText(R.string.reader_detail_night);
            int bg_model = SPUtil.getInt("bg_model", 0);
            setBgBtnState(bg_model, true);
        }else{
            reader_tx_allday.setText(R.string.reader_detail_day);
        }
    }

}
